from flask import current_app
from app.persistence.HouseImage import HouseImage
from datetime import datetime
from app.extensions import db


# def create_house_image(house_id, image_url, is_cover=False):
#     with current_app.app_context():
#         try:
#             if is_cover:
#                 HouseImage.query.filter_by(houseid=house_id, is_cover=True).update({'is_cover': False})
#                 db.session.commit()
#
#             new_image = HouseImage(
#                 houseid=house_id,
#                 image_url=image_url,
#                 is_cover=is_cover
#             )
#             db.session.add(new_image)
#             db.session.commit()
#             db.session.refresh(new_image)
#             return new_image
#         except Exception as e:
#             db.session.rollback()
#             current_app.logger.error(f"Error creating house image: {str(e)}")
#             return None

def create_house_image(house_id, image_url, is_cover=False):
    with current_app.app_context():
        try:
            # 只有当明确设置为封面时才更新其他图片
            if is_cover:
                # 检查是否已有封面图片
                existing_cover = HouseImage.query.filter_by(
                    houseid=house_id,
                    is_cover=True
                ).first()

                if existing_cover:
                    # 取消当前封面
                    existing_cover.is_cover = False
                    db.session.add(existing_cover)

            # 创建新图片记录
            new_image = HouseImage(
                houseid=house_id,
                image_url=image_url,
                is_cover=is_cover
            )
            db.session.add(new_image)
            db.session.commit()
            db.session.refresh(new_image)
            return new_image
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"Error creating house image: {str(e)}")
            return None


def get_image_by_id(image_id):
    with current_app.app_context():
        image = HouseImage.query.filter_by(imageid=image_id).first()
        return image

def get_images_by_house(house_id):
    with current_app.app_context():
        images = HouseImage.query.filter_by(houseid=house_id).order_by(HouseImage.upload_time.desc()).all()
        return images

def get_cover_image(house_id):
    with current_app.app_context():
        cover = HouseImage.query.filter_by(houseid=house_id, is_cover=True).first()
        return cover

def update_image(image_id, **kwargs):
    from app import db
    with current_app.app_context():
        image = HouseImage.query.filter_by(imageid=image_id).first()
        if not image:
            return False

        # If setting as cover, unset any existing cover for this house
        if kwargs.get('is_cover', False):
            HouseImage.query.filter_by(houseid=image.houseid, is_cover=True).update({'is_cover': False})
            db.session.commit()

        allowed_fields = ['image_url', 'is_cover']
        for field, value in kwargs.items():
            if field in allowed_fields and hasattr(image, field):
                setattr(image, field, value)

        try:
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"Error updating house image: {str(e)}")
            return False

def delete_image(image_id):
    from app import db
    with current_app.app_context():
        image = HouseImage.query.filter_by(imageid=image_id).first()
        if not image:
            return False

        try:
            db.session.delete(image)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"Error deleting house image: {str(e)}")
            return False

def update_house_image(imageid, **kwargs):
    from app import db
    with current_app.app_context():
        image = HouseImage.query.filter_by(imageid=imageid).first()
        if not image:
            return False

        if 'image_url' in kwargs:
            image.image_url = kwargs['image_url']
        if 'is_cover' in kwargs:
            image.is_cover = kwargs['is_cover']

        db.session.commit()
        return True


def delete_house_image(imageid):
    from app import db
    with current_app.app_context():
        image = HouseImage.query.filter_by(imageid=imageid).first()
        if not image:
            return False

        db.session.delete(image)
        db.session.commit()
        return True